package com.cyt.wx.service.impl;

import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.wx.dao.WxAccountDao;
import com.cyt.wx.dao.WxApplyDao;
import com.cyt.wx.model.po.WxAccount;
import com.cyt.wx.model.po.WxApply;
import com.cyt.wx.model.vo.WxAccountVo;
import com.cyt.wx.model.vo.WxApplyVo;
import com.cyt.wx.service.WxAccountService;
import com.cyt.wx.service.WxApplyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 微信模块-公众号管理Service层实现类
 *
 * @author rong yuan
 * @date 2019-8-15 11:46:26
 */
@Service("wxAccountService")
public class WxAccountServiceImpl extends BaseServiceImpl<WxAccount> implements WxAccountService {

    @Resource
    private WxAccountDao wxAccountDao;
    @Resource
    private WxApplyDao wxApplyDao;
    @Resource
    private WxApplyService wxApplyService;

    @Autowired
    public void setBaseDao(WxAccountDao wxAccountDao) {
        this.baseDao = wxAccountDao;
    }

    /**
     * 分页查询
     *
     * @param wxAccountVo 接受参数对象
     * @param pageNum     分页数
     * @param pageSize    每页显示条数
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-8-15 11:46:26
     */
    @Override
    public ReturnResult page(WxAccountVo wxAccountVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<WxAccountVo> list = wxAccountDao.selectByCondition(wxAccountVo);
        PageInfo<WxAccountVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * list查询
     *
     * @param wxAccountVo 接受参数对象
     * @return List<WxAccountVo>
     * @author rong yuan
     * @date 2019-8-15 15:07
     */
    @Override
    public List<WxAccountVo> list(WxAccountVo wxAccountVo) {
        return wxAccountDao.selectByCondition(wxAccountVo);
    }

    /**
     * 查询对象集合
     *
     * @param wxAccountVo 对象
     * @return List 对象集合
     * @author shengQiang Yu
     * @date 2019-8-7 9:30:42
     */
    @Override
    public List<WxAccount> listExample(WxAccountVo wxAccountVo) {
        Example example = new Example(WxAccount.class);
        example.setOrderByClause(" create_time desc");
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAccountVo.getId())) {
            criteria.andEqualTo("id", wxAccountVo.getId());
        }
        if (StringUtils.isNotBlank(wxAccountVo.getUserId())) {
            criteria.andEqualTo("userId", wxAccountVo.getUserId());
        }
        if (StringUtils.isNotBlank(wxAccountVo.getAccountType())) {
            criteria.andEqualTo("accountType", wxAccountVo.getAccountType());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        return wxAccountDao.selectByExample(example);
    }

    /**
     * 添加或更新
     *
     * @param wxAccountVo 参数接受对象
     * @param sysUser     当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-8-15 11:46:26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(WxAccountVo wxAccountVo, SysUser sysUser) {
        if (StringUtils.isBlank(wxAccountVo.getId())) {
            WxAccount wxAccount = new WxAccount(sysUser);
            wxAccount.setUserId(sysUser.getId());
            wxAccount.setAccountType(wxAccountVo.getAccountType());
            wxAccount.setName(wxAccountVo.getName());
            wxAccount.setAppId(wxAccountVo.getAppId());
            wxAccount.setAppSecret(wxAccountVo.getAppSecret());
            wxAccount.setStatus(wxAccountVo.getStatus());
            wxAccount.setAccessToken(null);
            wxAccount.setAccessTokenEndTime(null);
            wxAccount.setJsTicket(null);
            wxAccount.setJsTicketEndTime(null);
            wxAccount.setExpiresIn(null);
            wxAccount.setPayKey(wxAccountVo.getPayKey());
            wxAccount.setPayMachId(wxAccountVo.getPayMachId());
            wxAccountDao.insert(wxAccount);
            syncUpdateWxApply(sysUser.getId(), wxAccount.getId());
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            WxAccount wxAccount = wxAccountDao.selectByPrimaryKey(wxAccountVo.getId());
            wxAccount.setUserId(sysUser.getId());
            wxAccount.setAccountType(wxAccountVo.getAccountType());
            wxAccount.setName(wxAccountVo.getName());
            wxAccount.setAppId(wxAccountVo.getAppId());
            wxAccount.setAppSecret(wxAccountVo.getAppSecret());
            wxAccount.setStatus(wxAccountVo.getStatus());
            wxAccount.setAccessToken(null);
            wxAccount.setAccessTokenEndTime(null);
            wxAccount.setJsTicket(null);
            wxAccount.setJsTicketEndTime(null);
            wxAccount.setExpiresIn(null);
            wxAccount.setPayKey(wxAccountVo.getPayKey());
            wxAccount.setPayMachId(wxAccountVo.getPayMachId());
            wxAccount.setUpdateTime(new Date());
            wxAccount.setUpdateUser(sysUser.getId());
            wxAccountDao.updateByPrimaryKey(wxAccount);
            syncUpdateWxApply(sysUser.getId(), wxAccount.getId());
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    private void syncUpdateWxApply(String userId, String accountId) {
        WxApplyVo wxApplyVo = new WxApplyVo();
        wxApplyVo.setUserId(userId);
        List<WxApply> wxApplyList = wxApplyService.listExample(wxApplyVo);
        if (CollectionUtils.isNotEmpty(wxApplyList)) {
            for (WxApply wxApply : wxApplyList) {
                wxApply.setAccountId(accountId);
                wxApplyDao.updateByPrimaryKey(wxApply);
            }
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param wxAccountVo 参数接受对象
     * @param sysUser     当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-8-15 11:46:26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(WxAccountVo wxAccountVo, SysUser sysUser) {
        //要修改的字段
        WxAccount wxAccount = new WxAccount();
        wxAccount.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        wxAccount.setUpdateUser(sysUser.getId());
        wxAccount.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(WxAccount.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxAccountVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxAccountVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        wxAccountDao.updateByExampleSelective(wxAccount, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }
}